import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:zhuanzu/page/base_page.dart';

import '../provider/post_list_provider.dart';
import '../widgets/post_grid_view.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool _isSearching = false;
  final TextEditingController _searchController = TextEditingController();

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final postProvider = Provider.of<PostListProvider>(context);

    return BasePage(
      child: Scaffold(
        backgroundColor: const Color(0xFFFFFFFF), // 纯白色
        appBar: AppBar(
          titleSpacing: 0,
          title: _isSearching
              ? TextField(
                  controller: _searchController,
                  autofocus: true,
                  decoration: InputDecoration(
                    hintText: '搜索帖子标题或关键词',
                    border: InputBorder.none,
                    prefixIcon: const Icon(Icons.search),
                    suffixIcon: IconButton(
                      icon: const Icon(Icons.clear),
                      onPressed: () {
                        if (_searchController.text.isNotEmpty) {
                          // 有文字，清空文字，重置搜索
                          _searchController.clear();
                          postProvider.updateSearch('');
                        } else {
                          // 没有文字，退出搜索模式
                          setState(() {
                            _isSearching = false;
                          });
                        }
                      },
                    ),
                  ),
                  textInputAction: TextInputAction.search,
                  onSubmitted: (value) {
                    postProvider.updateSearch(value);
                  },
                  onChanged: (value) {
                    postProvider.updateSearch(value);
                  },
                )
              : Row(
                  children: [
                    const Padding(
                      padding: EdgeInsets.only(left: 12, right: 22),
                      child: Text(
                        '首页',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),

                    ToggleButtons(
                      isSelected: [
                        postProvider.sortBy == 'createdAt',
                        postProvider.sortBy == 'like',
                      ],
                      onPressed: (index) {
                        if (index == 0) postProvider.updateSort('createdAt');
                        if (index == 1) postProvider.updateSort('like');
                      },
                      borderRadius: BorderRadius.circular(8),
                      constraints: const BoxConstraints(
                        minHeight: 32,
                        minWidth: 56,
                      ),
                      children: const [Text("最新"), Text("最热")],
                    ),
                    const Spacer(),
                    IconButton(
                      icon: const Icon(Icons.search),
                      onPressed: () {
                        setState(() {
                          _isSearching = true;
                        });
                      },
                    ),
                  ],
                ),
          elevation: 0,
        ),
        body: const PostGridView(),
        floatingActionButton: FloatingActionButton(
          onPressed: () async {
            final result = await context.push('/publish');
            if (result == true) {
              postProvider.refreshPosts();
            }
          },
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}
